package com.besttone.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.solr.common.SolrDocument;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhengzhenzhen on 2016/11/16.
 */
public class HbaseObject {

    /**
     * cell转换成bean(根据bean的类型选择不同转换方法)
     * @param map
     * @param clazz
     * @return
     */
    public static Object toBean(Map<String,Cell> map, Class clazz) {
        Object o = null;
        try {
            o = clazz.newInstance();
        } catch (InstantiationException e1) {
            e1.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }
        Field[] fields = clazz.getDeclaredFields();
        Cell cell=null;
        for (Field field : fields) {
            try {
                cell=map.get(field.getName());
            if(field.getType()==Long.class){
                Long longValue=Bytes.toLong(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                BeanUtils.setProperty(o, field.getName(), longValue);
            }else if(field.getType()==String.class){
                String strValue = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                BeanUtils.setProperty(o, field.getName(), strValue);
            }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return o;
    }

    /**
     * map存储key=字段名称,value=cell,用于之后的bean映射
     * @param ceList
     * @return
     */
    public static Map<String,Cell> getMapFromCell(List<Cell> ceList){
        Map<String,Cell> map=new HashMap<String,Cell>();
        for (Cell cell : ceList) {
            map.put(Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(),
                    cell.getQualifierLength()),cell);
            System.out.println(cell);
        }
        return map;
    }
}
